package tool

import (
	"go_essential/database"
	"go_essential/entity"
	"math/rand"
	"time"

	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
)

func GetUUID() string {
	// 生成UUID并返回
	uuid := uuid.New().String()
	return uuid
}

func GetCurrentTime() string {
	// 获取当前时间并返回
	return time.Now().Format("2006-01-02 15:04:05")
}

// 验证手机号
func ValidatePhone(phone string) bool {
	return len(phone) == 11
}

// 判断手机号是否已经存在
func IsPhoneExists(phone string) bool {
	// 查询数据库中是否存在该手机号
	userList := []entity.User{}
	database.MDB.Raw("select * from tb_user where phone = ?", phone).Scan(&userList)
	return len(userList) != 0
}

// 验证密码
func ValidatePassword(password string) bool {
	return len(password) >= 6
}

// 获取指定长度的随机字符串
func RandomString(length int) string {
	var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
	result := make([]byte, length)

	// rand.Seed(time.Now().Unix())
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]
	}
	return string(result)
}

// 密码加密
func HashPassword(password string) string {
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return password
	}
	return string(hashPassword)
}

// 密码解密
func CheckPassword(password string, hashPassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hashPassword), []byte(password))
	return err == nil
}
